package com.book.web.controller.system;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.book.common.core.controller.BaseController;
import com.book.common.core.page.TableDataInfo;
import com.book.system.domain.Task;
import com.book.system.domain.UserTaskCompletion;
import com.book.system.service.ITaskService;
import com.book.system.service.IUserTaskCompletionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Bigboss
 * @create 2024-11-10 17:10
 */
@Api(tags = "用户完成任务信息记录表")
@RestController
@RequestMapping("/system/completion")
public class SysUserTaskCompletionController extends BaseController {

    private final IUserTaskCompletionService userTaskCompletionService;
    private final ITaskService taskService;

    public SysUserTaskCompletionController(IUserTaskCompletionService userTaskCompletionService, ITaskService taskService) {
        this.userTaskCompletionService = userTaskCompletionService;
        this.taskService = taskService;
    }

    /**
     * 获取用户完成情况信息列表
     * @param entity
     * @return
     */
    @ApiOperation(value = "获取用户完成情况信息列表，权限：system:completion:list")
    @PreAuthorize("@ss.hasPermi('system:completion:list')")
    @GetMapping("/selectList")
    public TableDataInfo selectList(UserTaskCompletion entity) {
        startPage();
        List<UserTaskCompletion> list = userTaskCompletionService.list(new LambdaQueryWrapper<UserTaskCompletion>()
                .orderByDesc(UserTaskCompletion::getCreateTime));
        //查询对应的任务信息
        if(ObjectUtil.isEmpty(list)){
            return getDataTable(Collections.EMPTY_LIST);
        }
        List<String> taskIds = list.stream().map(UserTaskCompletion::getTaskId).distinct().collect(Collectors.toList());
        List<Task> tasks = taskService.listByIds(taskIds);
        Map<String, Task> taskMap = tasks.stream().collect(Collectors.toMap(Task::getId, Function.identity()));
        list.stream().forEach(item -> item.setTask(taskMap.getOrDefault(item.getTaskId(),null)));
        return getDataTable(list);
    }
}
